import { RCSPOpSystemInfo, RCSPOpWatch, RCSPOpWatchDial } from "../../../../lib/rcsp-impl/rcsp";
import { OPDirectoryBrowse, OPLargerFileTrans } from "../../../../jl_lib/jl-rcsp-op/jl_op_watch_1.1.0";
import api from "../../../../api/index";
const i18n = require('../../../../i18n/index');

// pages/function_test/dial_operate/dial_add_background/index.ts
Page({

    /**
     * 页面的初始数据
     */
    data: {
        l10n: {},
        isTransfering: false,
        transferProgressText: "",
        transferProgress: 0  // 添加数字进度
    },
    devScreenWidth: 240,
    devScreenHeight: 280,

    ensureLang() {
        try {
            const saved = wx.getStorageSync('app:lang');
            const cur = i18n.getLang && i18n.getLang();
            if (saved && saved !== cur && i18n.setLang) i18n.setLang(saved);
        } catch (_) {}
    },
    updateTexts() {
        const t = (k: string, p?: any) => i18n.t('dial.'+k,p);
        this.setData({ l10n: {
            sectionTitle: t('sectionTitle'),
            chooseTitle: t('chooseTitle'),
            chooseDesc: t('chooseDesc'),
            chooseBtn: t('chooseBtn'),
            progressSection: t('progressSection'),
            uploadProgress: t('uploadProgress'),
            transferring: t('transfering'),
            tipText: t('tipText')
        }});
        wx.setNavigationBarTitle({ title: t('title') });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options: any) {
        this.ensureLang();
        this.updateTexts();
        console.log('dial_add_background页面加载', options);
        
        RCSPOpWatch?.getFlashInfo().then((res) => {
            this.devScreenWidth = res.width
            this.devScreenHeight = res.height
            console.log("devScreenWidth : " + this.devScreenWidth);
            console.log("devScreenHeight : " + this.devScreenHeight);
            
            // 如果是从设备页面跳转过来，自动触发方式一
            if (options?.fromDevice === 'true') {
                console.log('检测到从设备页面跳转，自动触发方式一');
                // 延迟一下确保页面渲染完成
                setTimeout(() => {
                    this.clickWay1();
                }, 500);
            }
        })
    },
    onUnload(){ 
        RCSPOpWatchDial?.cancelAddWatchResourseFile() 
    }, 
    saveFile(fs: WechatMiniprogram.FileSystemManager, filePath: string, data: Uint8Array) {
        fs.writeFileSync(filePath, data.buffer)
        console.log("writeFileSync : ", data);
        console.log("filePath : ", filePath);

        wx.saveImageToPhotosAlbum({
            filePath: filePath,
            success() {
                wx.showToast({
                    title: i18n.t('dial.saveSuccess')
                })
            },
            fail() {
                wx.showToast({
                    title: i18n.t('dial.saveFailed'),
                    icon: 'none'
                })
            }
        })
    },
    onShow() {
        console.log('表盘背景设置页面显示')
        
        // 检查是否从裁剪页面跳转过来
        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        const options = currentPage.options || {}
        
        console.log('当前页面参数:', options)
        console.log('页面栈:', pages.map(p => p.route))
        
        if (options.fromCut === 'true') {
            console.log('检测到从裁剪页面跳转，处理裁剪数据')
            // 从全局变量获取裁剪数据
            const app = getApp()
            console.log('全局数据对象:', app.globalData)
            console.log('全局数据中的dialBgData:', app.globalData?.dialBgData)
            
            if (app.globalData && app.globalData.dialBgData) {
                console.log('获取到裁剪数据，数据大小:', app.globalData.dialBgData.byteLength)
                console.log('开始处理裁剪数据')
                this._handleDialBgData(app.globalData.dialBgData)
                // 清除全局数据
                delete app.globalData.dialBgData
                console.log('已清除全局数据')
            } else {
                console.log('未找到裁剪数据，全局数据为空或没有dialBgData字段')
            }
        } else {
            console.log('不是从裁剪页面跳转过来的')
            // 🆕 清理可能残留的临时图片路径
            const app = getApp()
            if (app.globalData?.tempDialBgImagePath) {
                console.log('🧹 清理残留的临时图片路径:', app.globalData.tempDialBgImagePath)
                delete app.globalData.tempDialBgImagePath
            }
        }
    },//裁剪图片
    clickWay1() {
        if (this.data.isTransfering) {
            return
        }
        RCSPOpSystemInfo?.getSystemInfo().then((systemInfo) => {
            if (systemInfo.callStatus == 1) {//手表通话中
                wx.showToast({
                    title: i18n.t('dial.callBusy'),
                    icon: 'none'
                })
            } else if (systemInfo.callStatus == 0) {//手表空闲
                wx.chooseImage({
                    count: 1,
                    sizeType: ['original'],
                    sourceType: ['album'], // 直接打开相册，不显示选择框
                    success: (res) => {
                        console.log("选择图片", res);
                        const imagePath = res.tempFilePaths[0]
                        // 跳转到照片编辑页面
                        wx.navigateTo({
                            url: '/pages/modifyPhoto/modify?fromDial=true&imagePath=' + encodeURIComponent(imagePath) + "&width=" + this.devScreenWidth + "&height=" + this.devScreenHeight
                        })
                    }
                })
            }
        })
    },//传输资源文件
    clickWay2() {
        if (this.data.isTransfering) {
            return
        }
        RCSPOpSystemInfo?.getSystemInfo().then((systemInfo) => {
            if (systemInfo.callStatus == 1) {//手表通话中
                wx.showToast({
                    title: i18n.t('dial.callBusy'),
                    icon: 'none'
                })
            } else if (systemInfo.callStatus == 0) {//手表空闲
                wx.chooseMessageFile({
                    count: 1,
                    success: (res) => {
                        const tempFilePaths = res.tempFiles
                        console.log("tempFilePaths : ", tempFilePaths);
                        const fs = wx.getFileSystemManager()
                        fs.getFileInfo({
                            filePath: tempFilePaths[0].path,
                            success: (res) => {
                                let fd = fs.openSync({
                                    filePath: tempFilePaths[0].path
                                })
                                let uint8 = new Uint8Array(res.size);
                                fs.read({
                                    fd: fd,
                                    arrayBuffer: uint8.buffer,
                                    length: res.size,
                                    success: (_res) => {
                                        const lastModifyTime = tempFilePaths[0].time
                                        const dialData = uint8
                                        console.log("读取文件成功", uint8);
                                        const fileName = tempFilePaths[0].name.toUpperCase()
                                        if (!fileName.startsWith("BGP_")) {
                                            wx.showToast({ title: i18n.t('dial.filenameError'), icon: 'error' })
                                            return
                                        }
                                        const transferCallback: OPLargerFileTrans.TransferTaskCallback = {
                                            onError: (code: number) => {
                                                this.setData({
                                                    transferProgressText: i18n.t('dial.transferFailed', { code }),
                                                    isTransfering: false,
                                                    transferProgress: 0
                                                })
                                            },
                                            onStart: () => {
                                                this.setData({
                                                    transferProgressText: i18n.t('dial.transferStart'),
                                                    isTransfering: true,
                                                    transferProgress: 0
                                                })
                                            },
                                            onProgress: (progress: number) => {
                                                this.setData({
                                                    transferProgressText: i18n.t('dial.transferProgress', { progress }),
                                                    transferProgress: progress // 更新数字进度
                                                })
                                            },
                                            onSuccess: () => {
                                                this.setData({
                                                    transferProgressText: i18n.t('dial.transferSuccess'),
                                                    isTransfering: false,
                                                    transferProgress: 100
                                                })
                                                
                                                // 传输成功后显示提示并返回设备页面
                                                wx.showToast({
                                                    title: i18n.t('dial.dialSetSuccess'),
                                                    icon: 'success',
                                                    duration: 2000
                                                });
                                                
                                                // 延迟返回设备页面
                                                setTimeout(() => {
                                                    // 🎨 设置表盘背景刷新标记
                                                    wx.setStorageSync('needRefreshDialBackground', true);
                                                    console.log('🎨 [表盘背景上传] 设置刷新标记');
                                                    
                                                    wx.navigateBack({
                                                        delta: 1,
                                                        fail: () => {
                                                            // 如果返回失败，尝试跳转到设备页面
                                                            wx.switchTab({
                                                                url: '/pages/device/device'
                                                            });
                                                        }
                                                    });
                                                }, 2000);
                                            },
                                            onCancel: (_code: number) => {
                                                this.setData({
                                                    transferProgressText: i18n.t('dial.transferCancel'),
                                                    isTransfering: false,
                                                    transferProgress: 0
                                                })
                                            }
                                        }
                                        RCSPOpWatchDial?.addWatchResourseFile(dialData, fileName, lastModifyTime, true, transferCallback).then((res) => {
                                            if (res instanceof OPDirectoryBrowse.File) {
                                                RCSPOpWatchDial?.setDialCustomBackground(res)
                                            }
                                        }).catch((_error) => {

                                        })
                                    }, complete: (_res) => {
                                        fs.close({ fd })
                                    }
                                })
                            }
                        })

                    }
                })
            }
        })
    },
    clickCancelTransfer() {
        RCSPOpWatchDial?.cancelAddWatchResourseFile()
    },
    //传输资源文件-苹果手机showModal有问题需要加延时处理//https://developers.weixin.qq.com/community/develop/doc/0002ae427e0990ebe13ec78245d800?highLine=wx.showModal%2520iOS
    _handleDialBgData(data: Uint8Array | ArrayBuffer){
        console.log("onDialBgData :  ", data);
        
        // 如果是ArrayBuffer，转换为Uint8Array
        let uint8Data: Uint8Array
        if (data instanceof ArrayBuffer) {
            uint8Data = new Uint8Array(data)
        } else {
            uint8Data = data
        }
        
        const lastModifyTime = (new Date()).getTime()
        console.log(" lastModifyTime " + lastModifyTime);
        
        // 为硬件设备使用不带后缀的文件名，为服务器上传使用带后缀的文件名
        const hardwareFileName = "BGP_W000"  // 硬件API使用
        const serverFileName = "BGP_W000.png"  // 服务器上传使用
        console.log("硬件文件名: " + hardwareFileName);
        console.log("服务器文件名: " + serverFileName);
        
        const transferCallback: OPLargerFileTrans.TransferTaskCallback = {
            onError: (code: number) => {
                this.setData({
                    transferProgressText: i18n.t('dial.transferFailed', { code }),
                    isTransfering: false,
                    transferProgress: 0
                })
            },
            onStart: () => {
                this.setData({
                    transferProgressText: i18n.t('dial.transferStart'),
                    isTransfering: true,
                    transferProgress: 0
                })
            },
            onProgress: (progress: number) => {
                this.setData({
                    transferProgressText: i18n.t('dial.transferProgress', { progress }),
                    transferProgress: progress // 更新数字进度
                })
            },
            onSuccess: () => {
                this.setData({
                    transferProgressText: i18n.t('dial.transferSuccess'),
                    isTransfering: false,
                    transferProgress: 100
                })
                
                // 传输成功后显示提示并直接跳转到设备页面
                wx.showToast({
                    title: i18n.t('dial.dialSetSuccess'),
                    icon: 'success',
                    duration: 2000
                });
                
                // �� 获取临时PNG图片路径并上传到服务器
                const app = getApp();
                const tempImagePath = app.globalData?.tempDialBgImagePath;
                
                if (tempImagePath) {
                    console.log('📤 开始上传临时PNG图片到服务器:', tempImagePath);
                    this._uploadPngImageToServer(tempImagePath, serverFileName).then(() => {
                        console.log('✅ 表盘背景PNG图片已同步到服务器');
                        // 清理临时图片路径
                        delete app.globalData.tempDialBgImagePath;
                                         }).catch((error: any) => {
                         console.warn('⚠️ 上传PNG图片到服务器失败，但设备设置成功:', error);
                     });
                } else {
                    console.warn('⚠️ 未找到临时PNG图片路径，跳过服务器上传');
                }
                
                // 延迟跳转到设备页面
                setTimeout(() => {
                    // 直接跳转到设备页面，而不是返回
                    // 🎨 设置表盘背景刷新标记
                    wx.setStorageSync('needRefreshDialBackground', true);
                    console.log('🎨 [表盘背景上传] 设置刷新标记');
                    
                    wx.switchTab({
                        url: '/pages/device/device',
                        success: () => {
                            console.log('成功跳转到设备页面')
                        },
                        fail: (error) => {
                            console.error('跳转到设备页面失败:', error)
                            // 如果switchTab失败，尝试navigateBack
                            wx.navigateBack({
                                delta: 1
                            });
                        }
                    });
                }, 2000);
            },
            onCancel: (_code: number) => {
                this.setData({
                    transferProgressText: i18n.t('dial.transferCancel'),
                    isTransfering: false,
                    transferProgress: 0
                })
            }
        }
        RCSPOpWatchDial?.addWatchResourseFile(uint8Data, hardwareFileName, lastModifyTime, true, transferCallback).then((res) => {
            console.log("🎨 [添加表盘资源文件] 结果:", res);
            if (res instanceof OPDirectoryBrowse.File) {
                console.log("🎨 [设置表盘背景] 开始设置自定义背景:", res.getName());
                RCSPOpWatchDial?.setDialCustomBackground(res).then((setResult) => {
                    console.log("✅ [设置表盘背景] 设置成功:", setResult);
                }).catch((setError) => {
                    console.error("❌ [设置表盘背景] 设置失败:", setError);
                });
            } else {
                console.warn("⚠️ [添加表盘资源文件] 返回结果不是File对象:", typeof res);
            }
        }).catch((error) => {
            console.error("❌ [添加表盘资源文件] 添加失败:", error);
        })
    },
    
    // 🆕 上传PNG图片文件到服务器
    async _uploadPngImageToServer(imagePath: string, fileName: string): Promise<void> {
        console.log('🌐 [_uploadPngImageToServer] 开始上传PNG图片到服务器');
        console.log('📁 图片路径:', imagePath, '文件名:', fileName);
        
        try {
            // 导入API模块
            const api = require('../../../../api/index').default;
            
            // 获取用户信息
            const userProfile = await api.getUserInfo();
            const userId = userProfile?.data?.data?.id || userProfile?.data?.id;
            
            if (!userId) {
                throw new Error('无法获取用户ID');
            }
            
            console.log('👤 用户ID:', userId);
            
            // 尝试获取当前连接的设备信息
            let deviceId = null;
            let deviceSn = null;
            
            try {
                // 从全局状态管理器获取当前设备信息
                const { RCSPManager } = require('../../../../lib/rcsp-impl/rcsp');
                const currentWrapper = RCSPManager.getCurrentRcspOperateWrapper();
                deviceId = currentWrapper?.deviceId;
                
                if (!deviceId) {
                    // 尝试从设备页面数据获取
                    const pages = getCurrentPages();
                    const devicePage = pages.find(page => page.route === 'pages/device/device');
                    if (devicePage && devicePage.data) {
                        const currentDevice = devicePage.data.currentDevice;
                        deviceId = currentDevice?.deviceId || currentDevice?.device_id;
                        deviceSn = currentDevice?.deviceSn || currentDevice?.device_sn;
                    }
                }
                
                console.log('📱 当前设备信息:', { deviceId: deviceId || '未知', deviceSn: deviceSn || '未知' });
            } catch (deviceError) {
                console.warn('⚠️ 获取设备信息失败:', deviceError);
            }
            
            console.log('📤 准备上传PNG文件:', {
                imagePath,
                fileName: fileName,
                userId,
                deviceId,
                deviceSn
            });
            
            // 使用微信小程序的uploadFile上传PNG图片
            console.log('🚀 使用wx.uploadFile上传PNG图片');
            
            // 构建表单数据
            const formData: any = {
                userId: String(userId),
                fileType: 'dial_background_png',
                category: 'dial_background',
                originalFileName: fileName
            };
            
            // 添加设备信息到表单数据中
            if (deviceId) {
                formData.deviceId = deviceId;
                console.log('📱 添加设备ID到上传数据:', deviceId);
            }
            
            if (deviceSn) {
                formData.deviceSn = deviceSn;
                console.log('📱 添加设备序列号到上传数据:', deviceSn);
            }
            
            const uploadResponse: any = await new Promise((resolve, reject) => {
                wx.uploadFile({
                    url: 'https://xhd.szxhdkj.com/api/files/upload',
                    filePath: imagePath,
                    name: 'file',
                    formData: formData,
                    header: {
                        'Content-Type': 'multipart/form-data'
                    },
                    success: (res) => {
                        console.log('📤 文件上传成功，服务器响应:', res);
                        resolve({
                            statusCode: res.statusCode,
                            data: res.data ? JSON.parse(res.data) : null
                        });
                    },
                    fail: (error) => {
                        console.error('📤 文件上传失败:', error);
                        reject(error);
                    }
                });
            });
            console.log('✅ 服务器响应:', uploadResponse);
            
            // 检查上传结果
            if (uploadResponse && uploadResponse.statusCode === 200) {
                const responseData = uploadResponse.data;
                if (responseData && (responseData.code === "200" || responseData.code === 200 || responseData.code === "201" || responseData.code === 201 || responseData.code === 0)) {
                    console.log('🎉 PNG表盘背景上传成功，服务器响应:', responseData);
                    
                    // 检查表盘背景是否成功更新到设备
                    if (responseData.data) {
                        const data = responseData.data;
                        
                        if (data.isDialBackground) {
                            if (data.dialBackgroundUpdated) {
                                console.log('✅ 表盘背景已成功更新到设备');
                                console.log('📱 使用的设备信息:', {
                                    userId: data.userId,
                                    deviceId: data.deviceId,
                                    deviceSn: data.deviceSn
                                });
                            } else {
                                console.warn('⚠️ 表盘背景上传成功，但未能更新到设备');
                                console.warn('💡 请检查设备绑定状态或稍后重试');
                            }
                        }
                        
                        // 保存服务器返回的文件信息
                        if (data.fileId || data.objectKey || data.accessUrl) {
                            const fileInfo = {
                                fileId: data.fileId,
                                objectKey: data.objectKey,
                                accessUrl: data.accessUrl,
                                fileName: data.fileName,
                                uploadTime: new Date().toISOString(),
                                isDialBackground: data.isDialBackground,
                                dialBackgroundUpdated: data.dialBackgroundUpdated,
                                deviceInfo: {
                                    userId: data.userId,
                                    deviceId: data.deviceId,
                                    deviceSn: data.deviceSn
                                }
                            };
                            wx.setStorageSync('dialBgFileInfo', fileInfo);
                            console.log('💾 已保存PNG文件信息:', fileInfo);
                        }
                    }
                    
                    return Promise.resolve();
                } else {
                    throw new Error(responseData?.message || `服务器处理失败，返回码: ${responseData?.code}`);
                }
            } else {
                throw new Error(`上传请求失败，HTTP状态码: ${uploadResponse?.statusCode}`);
            }
            
        } catch (error: any) {
            console.error('❌ [_uploadPngImageToServer] PNG上传失败:', error);
            
            // 记录上传失败信息到本地
            const failedUpload = {
                fileName: fileName + '.png',
                imagePath: imagePath,
                failTime: new Date().toISOString(),
                error: error instanceof Error ? error.message : '未知错误',
                type: 'png'
            };
            
            try {
                const failedUploads = wx.getStorageSync('failedDialBgUploads') || [];
                failedUploads.push(failedUpload);
                if (failedUploads.length > 5) {
                    failedUploads.splice(0, failedUploads.length - 5);
                }
                wx.setStorageSync('failedDialBgUploads', failedUploads);
                console.log('📝 已记录PNG上传失败信息供后续重试');
            } catch (storageError) {
                console.warn('⚠️ 保存失败记录时出错:', storageError);
            }
            
            return Promise.reject(error);
        }
    },

})